package com.krt.webapp.until;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import com.krt.webapp.R;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;


/**
 * @author Administrator
 */
public class BaseUtil {

    private final static String[] PHONE_INFO = new String[]{Phone.DISPLAY_NAME, Phone.NUMBER};
    private Context context;
    private String t, m, o, c;

    private static Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

    private static final String CTWAP = "ctwap";
    private static final String CMWAP = "cmwap";
    private static final String WAP_3G = "3gwap";
    private static final String UNIWAP = "uniwap";
    private static final int TYPE_NET_WORK_DISABLED = 0;// 网络不可用
    private static final int TYPE_CM_CU_WAP = 4;// 移动联通wap10.0.0.172
    private static final int TYPE_CT_WAP = 5;// 电信wap 10.0.0.200
    private static final int TYPE_OTHER_NET = 6;// 电信,移动,联通,wifi 等net网络
    private static final int TYPE_WIFI_NET = 7;//wifi

    public BaseUtil(Context context) {
        this.context = context;
    }

    public static String utf2gbk(String utf) throws UnsupportedEncodingException {
        return new String(utf.getBytes("UTF-8"), "utf-8");
    }


    /**
     * 判断GPS是否开启
     *
     * @return
     */
    public boolean isOpenGPS() {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * wifi链接状态
     *
     * @return 1：wifi已链接
     * 2：wifi未链接
     * 0：wifi未开启
     */
    public int netmod() {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo activeInfo = manager.getActiveNetworkInfo();
        if (activeInfo == null) {
            return 0;
        } else {
            if (wifiInfo.isConnected()) {
                return 1;
            } else {
                return 2;
            }
        }
    }

    /***
     * 判断Network具体类型（联通移动wap，电信wap，其他net）
     *
     * */
    public int checkNetworkType() {
        try {
            final ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo mobNetInfoActivity = connectivityManager
                    .getActiveNetworkInfo();
            if (mobNetInfoActivity == null || !mobNetInfoActivity.isAvailable()) {


                // 注意一：
                // NetworkInfo 为空或者不可以用的时候正常情况应该是当前没有可用网络，
                // 但是有些电信机器，仍可以正常联网，
                // 所以当成net网络处理依然尝试连接网络。
                // （然后在socket中捕捉异常，进行二次判断与用户提示）。

                Log.i("aaa", "=====================>无网络");
                return TYPE_NET_WORK_DISABLED;
            } else {

                // NetworkInfo不为null开始判断是网络类型

                int netType = mobNetInfoActivity.getType();
                if (netType == ConnectivityManager.TYPE_WIFI) {
                    // wifi net处理
                    Log.i("aaa", "=====================>wifi网络");
                    return TYPE_WIFI_NET;
                } else if (netType == ConnectivityManager.TYPE_MOBILE) {


                    // 注意二：
                    // 判断是否电信wap:
                    //不要通过getExtraInfo获取接入点名称来判断类型，
                    // 因为通过目前电信多种机型测试发现接入点名称大都为#777或者null，
                    // 电信机器wap接入点中要比移动联通wap接入点多设置一个用户名和密码,
                    // 所以可以通过这个进行判断！

                    final Cursor c = context.getContentResolver().query(
                            PREFERRED_APN_URI, null, null, null, null);
                    if (c != null) {
                        c.moveToFirst();
                        final String user = c.getString(c
                                .getColumnIndex("user"));
                        if (!TextUtils.isEmpty(user)) {
                            Log.i("aaa",
                                    "=====================>代理："
                                            + c.getString(c
                                            .getColumnIndex("proxy")));
                            if (user.startsWith(CTWAP)) {
                                Log.i("aaa", "=====================>电信wap网络");
                                return TYPE_CT_WAP;
                            }
                        }
                    }
                    c.close();


                    // 注意三：
                    // 判断是移动联通wap:
                    // 其实还有一种方法通过getString(c.getColumnIndex("proxy")获取代理ip
                    //来判断接入点，10.0.0.172就是移动联通wap，10.0.0.200就是电信wap，但在
                    //实际开发中并不是所有机器都能获取到接入点代理信息，例如魅族M9 （2.2）等...
                    // 所以采用getExtraInfo获取接入点名字进行判断

                    String netMode = mobNetInfoActivity.getExtraInfo();
                    Log.i("aaa", "netMode ================== " + netMode);
                    if (netMode != null) {
                        // 通过apn名称判断是否是联通和移动wap
                        netMode = netMode.toLowerCase();
                        if (netMode.equals(CMWAP) || netMode.equals(WAP_3G)
                                || netMode.equals(UNIWAP)) {
                            Log.i("aaa", "=====================>移动联通wap网络");
                            return TYPE_CM_CU_WAP;
                        }

                    }

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return TYPE_OTHER_NET;
        }

        return TYPE_OTHER_NET;

    }


    /**
     * 创建文件夹
     *
     * @param filePath文件夹路径
     */
    public static void makeRootDirectory(String filePath) {
        File file = null;
        String[] dirs = filePath.split("/");
        String mdpath = Environment.getExternalStorageDirectory() + "/";
        for (int i = 0; i < dirs.length; i++) {
            mdpath = mdpath + dirs[i] + "/";
            Log.w("path", mdpath);
            file = new File(mdpath);
            if (!file.exists()) {
                file.mkdir();
            }
        }
    }

    /**
     * 清除缓存
     */
    public void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }

    /**
     * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param
     * context
     */
    public void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }


    /**
     * 图片缩放
     *
     * @param path
     * @return
     */
    public Bitmap sfPIC(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        //获取图片原始高宽
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//		if (bitmap == null) {
//			Log.w("pic", "path=" + path);
//			Log.w("pic", "null");
//			return null;
//		}

        float realW = options.outWidth;
        Log.w("pic", "图片原始宽度：" + realW + ";图片原始高度：" + options.outHeight);
        //获得缩放比例
        int scale = (int) realW / 300;
        if (scale < 1) {
            scale = 1;
        }
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;

        bitmap = BitmapFactory.decodeFile(path, options);
        Log.w("pic", "图片宽度：" + bitmap.getWidth() + ";图片高度：" + bitmap.getHeight());
        return bitmap;
    }

    /**
     * 图片缩放
     *
     * @param path
     * @return
     */
    public Bitmap sfPIC2(String path) {
        Bitmap bitmap = null;

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, opts);
        opts.inSampleSize = computeSampleSize(opts, -1, 3000 * 400);
        opts.inJustDecodeBounds = false;
        try {
            bitmap = BitmapFactory.decodeFile(path, opts);
        } catch (OutOfMemoryError err) {
            err.printStackTrace();
        }

        //原始宽度
        float realW = bitmap.getWidth();
        Log.w("pic", "图片原始宽度：" + realW + ";图片原始高度：" + bitmap.getHeight());
        //获得缩放比例
        float scale = ((float) 300) / realW;
        if (scale > 1) {
            return bitmap;
        } else {
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);

            Bitmap nBitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            Log.w("pic", "图片宽度：" + nBitmap.getWidth() + ";图片高度：" + nBitmap.getHeight());
            return nBitmap;
        }
    }

    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    public static int computeInitialSampleSize(BitmapFactory.Options options,
                                               int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 :
                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 :
                (int) Math.min(Math.floor(w / minSideLength),
                        Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) &&
                (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 从路径获取图片名称
     */
    public String GetFileName(String path) {
        return path.substring(path.length() - new StringBuffer(path).reverse().indexOf("/"));
    }


    /**
     * 判断当前应用是否在前台运行
     */
    public boolean isRunningForeground() {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String pname = cn.getPackageName();
        if (!TextUtils.isEmpty(pname) && pname.equals(context.getPackageName())) {
            return true;
        }
        return false;
    }

    /**
     * 拨打电话
     *
     * @param PhoneNo
     * @return
     */
    public Intent CallNo(String PhoneNo) {
        Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + PhoneNo));
        return intent;
    }


    /**
     * 获取图片背景圆
     *
     * @param colorid
     * @return
     */
    public ShapeDrawable getShapeDrawable(int colorid) {
        ShapeDrawable sd = new ShapeDrawable(new OvalShape());
        sd.getPaint().setColor(context.getResources().getColor(colorid));
        return sd;
    }


    /**
     * 生成一個按鈕的弹出框
     *
     * @param title      标题
     * @param titleicon  标题图标
     * @param message    正文
     * @param buttonword 按钮文字
     * @param btListener 按钮点击监听时间
     */
    public void ShowAD1(String title, int titleicon, String message, String buttonword, OnClickListener btListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        t = title.trim().equals("") ? context.getResources().getString(R.string.app_name) : title.trim();
        o = buttonword.trim().equals("") ? "确定" : buttonword.trim();

        builder.setTitle(t);
        builder.setMessage(message);
        if (titleicon != 0) {
            builder.setIcon(titleicon);
        }
        if (btListener == null) {
            builder.setPositiveButton(o, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO 自动生成的方法存根
                    dialog.dismiss();
                }
            });
        } else {
            builder.setPositiveButton(o, btListener);
        }
        builder.create().show();
    }

    /**
     * 生成两个按钮的弹出框
     *
     * @param title         标题
     * @param titleicon     标题图标
     * @param message       正文
     * @param OKBt          确认按钮文字
     * @param OKListener    确认按钮点击监听事件
     * @param CanelBt       取消按钮文字
     * @param canelListener 取消按钮点击监听事件
     */
    public void ShowAD2(String title, int titleicon, String message, String OKBt, OnClickListener OKListener, String CanelBt, OnClickListener canelListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        t = title.trim().equals("") ? context.getResources().getString(R.string.app_name) : title.trim();
        o = OKBt.trim().equals("") ? "确定" : OKBt.trim();
        c = CanelBt.trim().equals("") ? "取消" : CanelBt.trim();

        builder.setMessage(message);
        builder.setTitle(t);
        if (titleicon != 0) {
            builder.setIcon(titleicon);
        }
        if (OKListener == null) {
            builder.setPositiveButton(o, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO 自动生成的方法存根
                    dialog.dismiss();
                }
            });
        } else {
            builder.setPositiveButton(o, OKListener);
        }
        if (canelListener == null) {
            builder.setNegativeButton(c, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO 自动生成的方法存根
                    dialog.dismiss();
                }
            });
        } else {
            builder.setNegativeButton(c, canelListener);
        }
        builder.create().show();
    }

    /**
     * 显示Toast消息框
     *
     * @param info 显示内容
     */
    public void showToast(String info) {
        Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
    }

    /**
     * 对网络连接状态进行判断
     *
     * @return true, 可用； false， 不可用
     */
    public boolean isOpenNetwork() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }

    //dp转像素单位
    public int dipToPx(int dip) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wmg = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wmg.getDefaultDisplay().getMetrics(dm);
        return (int) (dip * dm.density + 0.5f);
    }

    //获取当前版本号
    public String getVersion() {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);

            return packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    /**
     * 二次加密
     *
     * @param msg
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String myEncrypt(String msg) throws UnsupportedEncodingException {
        return TextUtils.isEmpty(msg) ? "" : AES.getAESEncrypt(MyBase64.Encrypt(msg), "s@d#f$g%h&4y5d2d");
    }

    /**
     * 二次解密
     *
     * @param msg
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String myDecrypt(String msg) throws UnsupportedEncodingException {
        return TextUtils.isEmpty(msg) ? "" : MyBase64.Decrypt(AES.getAESDecrypt(msg, "s@d#f$g%h&4y5d2d"));
    }

    /**
     * 获取assets下的json文件内容
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


}
